import SocketServerAdapter from './socketServerAdapter.js'
import { useUserStore } from '@/stores/user.js'

class GlobalWebSocketManager {
  constructor() {
    this.socketAdapter = null
    this.isInitialized = false
    this.connectionPromise = null
  }

  // 获取或创建WebSocket连接
  async getConnection() {
    console.log('getConnection 被调用')
    console.log('当前 socketAdapter:', this.socketAdapter)
    console.log('当前连接状态:', this.getConnectionStatus())
    console.log('是否已连接:', this.isConnected())
    
    // 如果已经有socketAdapter实例且已连接，直接返回
    if (this.socketAdapter && this.isConnected()) {
      console.log('使用现有WebSocket连接')
      return this.socketAdapter
    }

    // 如果有正在进行的连接，等待它完成
    if (this.connectionPromise) {
      console.log('等待现有连接建立')
      return this.connectionPromise
    }

    // 如果有socketAdapter实例但未连接，检查WebSocketManager的实际状态
    if (this.socketAdapter && !this.isConnected()) {
      console.log('发现未连接的socketAdapter，检查实际连接状态')
      try {
        const status = this.socketAdapter.getConnectionStatus()
        console.log('当前连接状态详情:', status)
        
        // 如果WebSocketManager显示已连接，直接返回
        if (status && status.connected === true) {
          console.log('WebSocketManager显示已连接，直接返回socketAdapter')
          return this.socketAdapter
        }
      } catch (error) {
        console.log('检查连接状态时出错，创建新连接:', error)
      }
    }

    console.log('创建新的WebSocket连接')
    this.connectionPromise = this.createConnection()
    return this.connectionPromise
  }

  // 创建连接
  async createConnection() {
    try {
      console.log('createConnection 开始创建连接...')
      this.socketAdapter = new SocketServerAdapter()
      console.log('SocketServerAdapter 实例已创建:', this.socketAdapter)
      
      // 设置连接状态监听
      this.socketAdapter.on('connection_status', (data) => {
        console.log('全局WebSocket连接状态变更:', data)
        if (data.connected) {
          // 连接成功后自动登录
          const userStore = useUserStore()
          const token = userStore.token || `user-token-${Date.now()}`
          this.socketAdapter.login(token)
          console.log('全局WebSocket连接成功，自动登录:', token)
        }
      })

      this.socketAdapter.on('connection_error', (err) => {
        console.log('全局WebSocket连接错误:', err)
        this.connectionPromise = null
      })

      this.socketAdapter.on('reconnect_failed', (err) => {
        console.log('全局WebSocket重连失败:', err)
        this.connectionPromise = null
      })

      // 建立连接 - 使用WebSocketManager的默认URL
      console.log('开始调用 socketAdapter.connect()...')
      const connectResult = await this.socketAdapter.connect()
      console.log('socketAdapter.connect() 完成，结果:', connectResult)
      
      // 等待连接真正建立
      if (connectResult) {
        // 等待连接状态变为已连接
        await new Promise((resolve, reject) => {
          const checkConnection = () => {
            const status = this.socketAdapter.getConnectionStatus()
            console.log('检查连接状态:', status)
            if (status.connected) {
              console.log('WebSocket连接已建立')
              resolve()
            } else {
              // 如果5秒内没有连接成功，则超时
              setTimeout(() => {
                const currentStatus = this.socketAdapter.getConnectionStatus()
                if (currentStatus.connected) {
                  console.log('WebSocket连接已建立')
                  resolve()
                } else {
                  console.log('WebSocket连接超时')
                  reject(new Error('WebSocket连接超时'))
                }
              }, 5000)
            }
          }
          
          // 立即检查一次
          checkConnection()
        })
      }
      
      this.isInitialized = true
      console.log('全局WebSocket连接初始化完成')
      
      return this.socketAdapter
    } catch (error) {
      console.error('创建WebSocket连接失败:', error)
      this.connectionPromise = null
      throw error
    }
  }

  // 获取当前连接状态
  getConnectionStatus() {
    if (!this.socketAdapter) {
      return { connected: false }
    }
    return this.socketAdapter.getConnectionStatus()
  }

  // 断开连接
  disconnect() {
    if (this.socketAdapter) {
      this.socketAdapter.disconnect()
      this.socketAdapter = null
      this.isInitialized = false
      this.connectionPromise = null
    }
  }

  // 检查是否已连接
  isConnected() {
    if (!this.socketAdapter) {
      return false
    }
    try {
      const status = this.socketAdapter.getConnectionStatus()
      return status && status.connected === true
    } catch (error) {
      console.error('检查连接状态时出错:', error)
      return false
    }
  }
}

// 创建全局实例
const globalWebSocket = new GlobalWebSocketManager()

export default globalWebSocket 